package cn.net.chenbao.medical;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.OnDismissListener;

import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cn.net.chenbao.medical.api.Api;
import cn.net.chenbao.medical.base.BaseActivity;
import cn.net.chenbao.medical.dialog.TwoSelectDialog;
import cn.net.chenbao.medical.mvp.MainP;
import cn.net.chenbao.medical.mvp.presenter.IMainP;
import cn.net.chenbao.medical.mvp.view.IMainV;
import cn.net.chenbao.medical.util.Consts;
import cn.net.chenbao.medical.util.DialogUtils;
import cn.net.chenbao.medical.util.SharedPreferenceUtils;
import cn.net.chenbao.medical.util.ZLog;
import cn.net.chenbao.medical.weight.CommonDialog;
import cn.net.chenbao.medical.xutils.ParamsUtils;
import cn.net.chenbao.medical.xutils.WWXCallBack;

public class MainActivity extends BaseActivity implements View.OnClickListener, IMainV {
    private TextView mTvDeviceId, mTvName;
    private int CURRENT_MODE;

    private CommonDialog mDialog;

    private IMainP mMainP;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        mMainP = new MainP(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isLoading = false;
        mStartDate = null;
        mEndDate = null;
        mPyFlag = -1;
    }

    private void initView() {
        findViewById(R.id.ll_jc).setOnClickListener(this);
        findViewById(R.id.ll_hsjj).setOnClickListener(this);
        findViewById(R.id.ll_nurse_sure).setOnClickListener(this);
        findViewById(R.id.ll_apothecary_sure).setOnClickListener(this);
        findViewById(R.id.ll_drug_withdrawal).setOnClickListener(this);
        findViewById(R.id.ll_exit).setOnClickListener(this);
        findViewById(R.id.ll_report).setOnClickListener(this);
        findViewById(R.id.ll_kbcc).setOnClickListener(this);
        mTvDeviceId = (TextView) findViewById(R.id.tv_device_id2);
        mTvDeviceId.setText(String.format(getString(R.string.device_id), MedicalApplication.getInstance().getDeviceId()));
        mTvName = (TextView) findViewById(R.id.tv_name);
        mTvName.setText(MedicalApplication.getInstance().getOperName());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        boolean sessionError = intent.getBooleanExtra(Consts.KEY_SESSION_ERROR,
                false);
        if (sessionError) {// session相关错误
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
    }


    private boolean isLoading;

    @Override
    public void onClick(View v) {
        if (!isLoading)
            isLoading = true;
        else
            return;
        switch (v.getId()) {
            case R.id.ll_report:
                isLoading = false;
                showTwoDialog();
                break;
            case R.id.ll_jc:
                mMainP.doAuthority(Consts.MODE_JC);
                break;
            case R.id.ll_hsjj:
                mMainP.doAuthority(Consts.MODE_HSJJ);
                break;
            case R.id.ll_nurse_sure: {
                mMainP.doAuthority(Consts.MODE_NURSE);
                break;
            }
            case R.id.ll_apothecary_sure: {
                mMainP.doAuthority(Consts.MODE_APOTHECARY);
                break;
            }
            case R.id.ll_drug_withdrawal: {
                mMainP.doAuthority(Consts.MODE_DRUG_WITHDRAWAL);
                break;
            }
            case R.id.ll_kbcc:
                mMainP.doAuthority(Consts.MODE_KBCC);
                break;
            case R.id.ll_exit: {
                isLoading = false;
                if (mDialog == null) {
                    mDialog = DialogUtils
                            .getCommonDialogTwiceConfirm(MainActivity.this,
                                    getString(R.string.exit_sure), true);
                    mDialog.getButtonRight().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                            mMainP.doLogOut();
                        }
                    });
                    mDialog.show();
                } else {
                    mDialog.show();
                }
                break;
            }
            default:
                isLoading = false;
                break;
        }
    }


    private Intent mIntent;

    private void intent(int mode) {
        mIntent = mIntent == null ? new Intent() : mIntent;
        mIntent.setClass(this, FunctionActivity.class);
        mIntent.putExtra(Consts.KEY_MODULE, mode);
        startActivity(mIntent);
    }

    private void intentToReport() {
        if (TextUtils.isEmpty(mStartDate) || TextUtils.isEmpty(mEndDate) || mPyFlag == -1)
            return;
        mIntent = mIntent == null ? new Intent() : mIntent;
        mIntent.setClass(this, ReportListActivity.class);
        mIntent.putExtra(Consts.KEY_MODULE, Consts.MODE_BB);
        mIntent.putExtra("startDate", mStartDate);
        mIntent.putExtra("endDate", mEndDate);
        mIntent.putExtra("pyFlag", mPyFlag);
        startActivity(mIntent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        ZLog.e(keyCode + "");
        switch (keyCode) {
            case 8:
                //键数字1<进仓>
                if (!isLoading)
                    isLoading = true;
                else
                    break;
                mMainP.doAuthority(Consts.MODE_JC);
                break;
            case 29:
            case 9:
                //键数字2<配液>
                if (!isLoading)
                    isLoading = true;
                else
                    break;
                mMainP.doAuthority(Consts.MODE_NURSE);
                break;
            case 32:
            case 10:
                //键数字3<出仓>
                if (!isLoading)
                    isLoading = true;
                else
                    break;
                mMainP.doAuthority(Consts.MODE_APOTHECARY);
                break;
            case 11:
            case 35:
                //键数字4<护士交接>
                if (!isLoading)
                    isLoading = true;
                else
                    break;
                mMainP.doAuthority(Consts.MODE_HSJJ);
                break;
            case 12:
            case 38:
                //键数字5<退药>
                if (!isLoading)
                    isLoading = true;
                else
                    break;
                mMainP.doAuthority(Consts.MODE_DRUG_WITHDRAWAL);
                break;
            case 13:
            case 41:
                //键数字6<查询报表>
                isLoading = false;
                showTwoDialog();
                break;
            case 14:
            case 44:
                //键数字5<退药>
                if (!isLoading)
                    isLoading = true;
                else
                    break;
                mMainP.doAuthority(Consts.MODE_KBCC);
                break;
            default:
                isLoading = false;
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (KeyEvent.ACTION_DOWN == event.getAction()) {
            switch (event.getKeyCode()) {
                case 19:
                    //上 下键
                    if (mTimePV != null && mTimePV.isShowing()) {
                        mSelectCalendar.add(Calendar.DAY_OF_MONTH, -1);
                        mTimePV.setEventDate(mSelectCalendar);
                    }
                    break;
                case 20:
                    //上 下键
                    if (mTimePV != null && mTimePV.isShowing()) {
                        mSelectCalendar.add(Calendar.DAY_OF_MONTH, 1);
                        mTimePV.setEventDate(mSelectCalendar);
                    }
                    break;
            }
            return super.dispatchKeyEvent(event);
        }

        if (KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_UP == event.getAction()) {
            if (isFlag) {
                isFlag = false;
                return true;
            }
            if (mTimePV != null && mTimePV.isShowing()) {
                mTimePV.returnData();
                mTimePV.dismiss();
                return true;
            }

        }
        return super.dispatchKeyEvent(event);
    }

    private TwoSelectDialog mTwoSelectDialog;
    private int mPyFlag = -1;//1.配液 0、2.空包
    private boolean isFlag;//确定回车键事件

    @Override
    public void showTwoDialog() {
        if (mTimePV != null && mTimePV.isShowing())
            mTimePV.dismiss();
        if (mTwoSelectDialog == null) {
            mTwoSelectDialog = new TwoSelectDialog(
                    MainActivity.this, R.style.DialogStyle);
            mTwoSelectDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    mPyFlag = mTwoSelectDialog.getResult();
                    showTimePicker();
                }
            });
            mTwoSelectDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    ZLog.e(keyCode + "");
                    if (KeyEvent.ACTION_DOWN == event.getAction()) {
                        switch (keyCode) {
                            case 19:
                            case 20:
                                //上 下键
                                if (mTwoSelectDialog != null && mTwoSelectDialog.isShowing()) {
                                    mTwoSelectDialog.setSex(!mTwoSelectDialog.getResult2());
                                }
                                break;
                        }
                    }
                    if (KeyEvent.KEYCODE_ENTER == keyCode && KeyEvent.ACTION_DOWN == event.getAction()) {
                        isFlag = true;
                        mTwoSelectDialog.dismiss();
                    }
                    return false;
                }
            });
        }
        mTwoSelectDialog.show();
    }

    private TimePickerView mTimePV;
    private Calendar mSelectCalendar;
    private boolean isEndDate;
    private String mStartDate, mEndDate;
    private SimpleDateFormat mSDF;

    @Override
    public void showTimePicker() {
        mSelectCalendar = Calendar.getInstance();

        mSDF = new SimpleDateFormat("yyyy-MM-dd");
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar startDate = Calendar.getInstance();
        startDate.set(mSelectCalendar.get(Calendar.YEAR) - 5, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(mSelectCalendar.get(Calendar.YEAR) + 3, 11, 30);
        //时间选择器
        mTimePV = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                if (isEndDate) {
                    mEndDate = mSDF.format(date);
                    isEndDate = false;
                    mTimePV.dismiss();
                } else {
                    mStartDate = mSDF.format(date);
                    isEndDate = true;
                }
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("", "月", "日", "", "", "")
                .isCenterLabel(false)
                .setDividerColor(ContextCompat.getColor(MainActivity.this, R.color.main_line_color))
                .setContentSize(15)
                .setTitleSize(13)
                .setDate(mSelectCalendar)
                .setRangDate(startDate, endDate)
                .setBgColor(0xFFFFFFFF)
                .setTitleBgColor(0xFFFFFFFF)
                .setSubCalSize(15)
                .setCancelText("取消")
                .setSubmitColor(ContextCompat.getColor(MainActivity.this, R.color.main_color))
                .setCancelColor(ContextCompat.getColor(MainActivity.this, R.color.black))
                .setTextColorOut(ContextCompat.getColor(MainActivity.this, R.color.black2))
                .setTextColorCenter(ContextCompat.getColor(this, R.color.main_color)) //设置选中项文字颜色
                .setDecorView(null)
                .build();
        mTimePV.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                if (isEndDate) {
                    showTimePicker();
                } else {
                    intentToReport();
                }
            }
        });
        if (isEndDate) {
            mTimePV.setTitleText("选择终止日期");
        } else {
            mTimePV.setTitleText("选择起始日期");
        }
        mTimePV.show();

    }

    @Override
    public void AuthoritySuccess(int mode) {
        intent(mode);
    }

    @Override
    public void LogOutSuccess() {
        startActivity(new Intent(MainActivity.this, LoginActivity.class));
        finish();
    }

    @Override
    public void loadFinish() {
        super.loadFinish();
        isLoading = false;
    }
}
